import {Component, Input} from '@angular/core';
import {ReplyModel} from '../reply-list/reply-list';
import {PopoverController, Content} from 'ionic-angular';
import {EmojiPopoverPage} from '../emoji-popover/emoji-popover';
import {EditorService} from "../../services/EditorService";
import {MediaPlugin, File} from 'ionic-native';
import {EmojiService} from "../../services/EmojiService";
import {CommentType} from "./comment-type";
import {AppService} from "../../services/AppService";
import {ContentCardType} from "../../model/content-card-type";


@Component({
  selector: 'reply-input',
  templateUrl: 'reply-input.html',
  providers: [EditorService, EmojiService]
})
export class ReplyInput {
  recordState: string = 'non_recording';

  _name: string;
  record_duration: number = 0;
  media_file: MediaPlugin;

  username: string = '';
  uid: number = 0;

  @Input()
  beforeReply: Function = null;
  @Input()
  afterReply: Function = null;

  currentReplyContent: string = '';
  recordIcon: string = 'mic';

  @Input()
  replies: Array<ReplyModel> = [];
  @Input()
  contentCardType: ContentCardType;
  @Input()
  postId: number;

  duration_timer: number = 0;
  voice_send_timer: number = 0;

  constructor(
    public popoverCtrl: PopoverController,
    private editorService: EditorService,
    private emojiService: EmojiService,
    private appService: AppService
  ) {
    appService.username.then(username => {
      this.username = username
    });
    appService.uid.then(uid => this.uid = uid);
  }


  @Input()
  set name(value) {
    this._name = value;
    if (value !== '') {
      this.editorService.getSource(this.name).subscribe(emoji_id => this.currentReplyContent += `[emoji-${emoji_id}]`);
    }
  }

  get name(): string {
    return this._name;
  }

  record(event: any) {
    this.recordState = 'recording';
    this.recordIcon = 'ios-mic-outline';
    this.media_file = new MediaPlugin('tmp_record.m4a');
    this.media_file.startRecord();
    this.duration_timer = setInterval(() => {
      this.record_duration ++;
    }, 1000);
    this.voice_send_timer = setTimeout(() => {
      if (this.recordState == 'recording')
      {
        this.media_file.stopRecord();
        this.prepareSend(null);
        this.recordState = 'non_recording';
      }
    }, 60000);

  }

  prepareSend(event: any) {
    if (this.recordState == 'recording') {
      this.recordState = 'after_record';
      this.recordIcon = 'md-arrow-round-up';
      this.media_file.stopRecord();
    }
  }

  clearRecordState(event: any) {
    this.recordState = 'non_recording';
    this.recordIcon = 'mic';
    this.record_duration = 0;
    clearInterval(this.duration_timer);
    clearTimeout(this.voice_send_timer);
    File.removeFile(File.tempDirectory, 'tmp_record.m4a');
  }

  cancelRecord(event: any) {
    this.clearRecordState(event);
  }

  sendRecord(event: any) {
    if (this.recordState == 'after_record') {
      this.doReply('voice');
      this.clearRecordState(event);
    }
  }

  doReply(type: string = 'text') {
    let content = '';
    let commentType: CommentType;

    if (type == 'text') {
      if (this.currentReplyContent === '') return;

      this.currentReplyContent = this.emojiService.escapeEmojiToEmojiElement(this.currentReplyContent);
      if (this.beforeReply != null) {
        this.beforeReply(this.currentReplyContent);
      }
      content = this.currentReplyContent;
      commentType = CommentType.TextComment;
    }
    else if (type == 'voice') {
      if (this.media_file === null) return;
      if (this.beforeReply != null) {
        this.beforeReply(this.media_file);
      }
      content = this.record_duration.toString();
      commentType = CommentType.VoiceComment;
    }
    else
    {
      throw new TypeError('type must equal to text or voice');
    }

    this.appService.replyPost(this.contentCardType, this.postId, content, commentType, 'tmp_record.m4a').then(resp => {
      this.replies.push(new ReplyModel(resp.commentId, this.currentReplyContent, this.username, this.uid, new Date(), 0, resp.additionText));
      if (this.afterReply != null) {
        this.afterReply(this.currentReplyContent);
      }
      this.currentReplyContent = '';
    });


  }

  presentEmojiPopover(event: any) {
    let popover = this.popoverCtrl.create(EmojiPopoverPage, {emojiInputName: this.name});
    popover.present({
      ev: event
    });
  }
}
